package com.gz.purchase.app;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gz.purchase.R;
import com.gz.purchase.adapter.InStorageHistoryAdapter;
import com.gz.purchase.adapter.SpinnerAdapter;
import com.gz.purchase.library.IAuthor;
import com.gz.purchase.library.IProduct;
import com.gz.purchase.library.listener.QueryInStorageHistorylistener;
import com.gz.purchase.library.listener.RequestCode;
import com.gz.purchase.library.pojo.CustomerSpinnerObject;
import com.gz.purchase.library.pojo.MoveInStorageItemInfo;
import com.gz.purchase.library.pojo.UserInfo;
import com.gz.purchase.library.util.Constants;
import com.gz.purchase.library.util.CrashHandler;
import com.gz.purchase.library.util.PreferenceModel;
import com.gz.purchase.util.ToastUtils;
import com.gz.purchase.widget.DoubleDatePickerDialog;
import com.gz.purchase.widget.FooterView;
import com.gz.purchase.widget.LoadingCover;
import com.gz.purchase.widget.SpinerPopWindow;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 *             入库历史记录界面
 *
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
         佛祖保佑       永无BUG
         佛曰:
                  写字楼里写字间，写字间里程序员；
                  程序人员写程序，又拿程序换酒钱。
                  酒醒只在网上坐，酒醉还来网下眠；
                  酒醉酒醒日复日，网上网下年复年。
                  但愿老死电脑间，不愿鞠躬老板前；
                  奔驰宝马贵者趣，公交自行程序员。
                  别人笑我忒疯癫，我笑自己命太贱；
                  不见满街漂亮妹，哪个归得程序员？
 */
public class InStorageHistoryActivity extends BaseActivity implements View.OnClickListener,
        LoadingCover.OnLoadingCoverRefreshListener, DoubleDatePickerDialog.OnDateSetListener,
        SpinerPopWindow.ISpinnerOnItemSelectListener,  PullToRefreshBase.OnRefreshListener,
        FooterView.OnFooterViewRefreshListener {
    private String TAG = InStorageHistoryActivity.class.getSimpleName();
    private UserInfo info ;
    private MyQueryInStorageHistorylistener myPullListener;
    private MyQueryInStorageHistorylistener myScrollListener;

    private List<MoveInStorageItemInfo> mDataList;
    private InStorageHistoryAdapter mAdapter;

    private ImageView iv_actionbar_up;
    private TextView tv_actionbar_title;
    private TextView tv_actionbar_deliveryName;

    private RelativeLayout rl_choice_for_time;
    private RelativeLayout rl_choice_for_status;
    private RelativeLayout rl_choice_for_order;
    private PullToRefreshListView mPulListView;
    private LoadingCover mLoadingCover;
    private Dialog mLoadingData;
    private FooterView mFooterView;

    // 时间选择
    private DoubleDatePickerDialog timeDialog;
    private Calendar mCalendar;

    // 状态选择
    private List<CustomerSpinnerObject> statusList ;
    private SpinnerAdapter statusSpinnerAdapter;
    private SpinerPopWindow statusSpinnerPopWindow;

    private String startTime;//开始时间
    private String endTime; // 结束时间

    private String status = null;// 状态
    private int order_type = -1;

    private int page ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_in_storage_history);
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        mActionBar.setCustomView(R.layout.common_activity_head_layout);//自定义ActionBar布局
        initView();
        initListener();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myPullListener.release();
        myScrollListener.release();
    }



    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.rl_choice_for_time:
                timeDialog.show();
                break;
            case R.id.rl_choice_for_status:
                statusSpinnerPopWindow.setWidth(rl_choice_for_status.getWidth());
                statusSpinnerPopWindow.showAsDropDown(rl_choice_for_status);
                break;
            case R.id.iv_actionbar_up:
                finish();
                break;
        }


    }

    @Override
    public void onLoadingCoverRefresh() {
        page = 1;
        startTime = null;
        endTime = null;
        status = null;
        IProduct.getInstance().inStorageHistoryQuery(startTime, endTime, status, order_type, page, myPullListener);
    }

    // 时间选择器的触发事件
    @Override
    public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear, int startDayOfMonth, DatePicker endDatePicker, int endYear, int endMonthOfYear, int endDayOfMonth) {
        startTime = String.format("%d-%d-%d",startYear,startMonthOfYear+1,startDayOfMonth);
        endTime = String.format("%d-%d-%d",endYear,endMonthOfYear+1,endDayOfMonth);
        CrashHandler.i(TAG, "开始时间=" + startTime + "结束时间=" + endTime);
        page = 1;
        status = null;
        mLoadingData.show();
        IProduct.getInstance().inStorageHistoryQuery(startTime, endTime, status, order_type, page, myPullListener);

    }

    // 状态选择器触发事件
    @Override
    public void onSpinnerItemClick(int position) {
        StatusInfo info = (StatusInfo) statusList.get(position);
        page = 1;
        startTime = null;
        endTime = null;
        status = info.getId();
        mLoadingData.show();
        IProduct.getInstance().inStorageHistoryQuery(startTime,endTime,status,order_type,page,myPullListener);


    }

    // 滑动加载更多触发事件
    @Override
    public void onFooterViewRefresh() {
        page++;
        IProduct.getInstance().inStorageHistoryQuery(startTime,endTime,status,order_type,page,myScrollListener);

    }

    public void initView(){
        info = IAuthor.getInstance().loadUserInfoSyn(PreferenceModel.getInt(Constants.PREFERENCE_USER_ID, -1));
        iv_actionbar_up = (ImageView) this.findViewById(R.id.iv_actionbar_up);
        tv_actionbar_title = (TextView) this.findViewById(R.id.tv_actionbar_title);
        tv_actionbar_deliveryName = (TextView) this.findViewById(R.id.tv_actionbar_deliveryName);

        rl_choice_for_time = (RelativeLayout) findViewById(R.id.rl_choice_for_time);
        rl_choice_for_status = (RelativeLayout) findViewById(R.id.rl_choice_for_status);
        rl_choice_for_order = (RelativeLayout) findViewById(R.id.rl_choice_for_order);
        mPulListView = (PullToRefreshListView) findViewById(R.id.list);
        mLoadingCover = (LoadingCover) findViewById(R.id.layout_loading_cover);

        mFooterView = (FooterView) LayoutInflater.from(this).inflate(R.layout.footer_view, null);
        mPulListView.getRefreshableView().addFooterView(mFooterView);

        mLoadingData = new Dialog(this,R.style.DialogTheme);
        mLoadingData.setContentView(R.layout.loading_data_dialog2);
        mLoadingData.setCanceledOnTouchOutside(false);
        mLoadingData.setCancelable(false);

        mCalendar = Calendar.getInstance();
        timeDialog = new DoubleDatePickerDialog(this,0,this,
                mCalendar.get(Calendar.YEAR),mCalendar.get(Calendar.MONTH),mCalendar.get(Calendar.DATE),true);

    }

    public void initListener() {
        myPullListener = new MyQueryInStorageHistorylistener(this,RequestCode.PULL);
        myScrollListener = new MyQueryInStorageHistorylistener(this,RequestCode.SCROLL);
        rl_choice_for_time.setOnClickListener(this);
        rl_choice_for_status.setOnClickListener(this);
        rl_choice_for_order.setOnClickListener(this);
        iv_actionbar_up.setOnClickListener(this);
        mLoadingCover.setOnLoadingCoverRefreshListener(this);
        mFooterView.setOnFooterViewRefreshListener(this);
        mPulListView.setOnRefreshListener(this);

    }

    public void initData(){
        tv_actionbar_title.setText("入库历史记录");
        if (info != null){
            tv_actionbar_deliveryName.setText(info.getName() + "：" + info.getUser_name());
        }

        mDataList = new ArrayList<MoveInStorageItemInfo>();
        mAdapter = new InStorageHistoryAdapter(mDataList,this);
        mPulListView.setAdapter(mAdapter);

        // 初始化"状态选择" 控件
        statusList = new ArrayList<CustomerSpinnerObject>();
        statusList.add(new StatusInfo(Define.IN_STORAGE_HISTORY_NORMAL,"正常"));
        statusList.add(new StatusInfo(Define.IN_STORAGE_HISTORY_CANCEL,"作废"));

        statusSpinnerAdapter = new SpinnerAdapter(this,statusList);
        statusSpinnerPopWindow = new SpinerPopWindow(this);
        statusSpinnerPopWindow.setAdatper(statusSpinnerAdapter);
        statusSpinnerPopWindow.setItemListener(this);

        onLoadingCoverRefresh();
    }

    @Override
    public void onRefresh(PullToRefreshBase refreshView) {
        onLoadingCoverRefresh();
    }

    // 数据获取回调监听器
    private static class MyQueryInStorageHistorylistener extends QueryInStorageHistorylistener {
        private InStorageHistoryActivity mOuter;

        public MyQueryInStorageHistorylistener(InStorageHistoryActivity mOuter,RequestCode requestCode) {
            super(requestCode);
            this.mOuter = mOuter;
        }

        public void release(){
            new WeakReference<InStorageHistoryActivity>(mOuter);
        }


        @Override
        public void onResponseSuccess(List<MoveInStorageItemInfo> list) {
            if (list == null){
                list = new ArrayList<MoveInStorageItemInfo>();
            }

            if (getRequestCode() == RequestCode.PULL){
                mOuter.mDataList.clear();
            }
            if (list.size() < Define.IN_OR_OUT_STORAGE_MAX_NUM){
                mOuter.mFooterView.onRefreshComplete();
                mOuter.mPulListView.setOnScrollListener(null);

            }else{
                mOuter.mFooterView.onRefreshSuccess();
                mOuter.mPulListView.setOnScrollListener(mOuter.mFooterView);
            }
            if (mOuter.mPulListView.isRefreshing()){
                mOuter.mPulListView.getLoadingLayoutProxy().refreshSuccess();
            }

            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }

            mOuter.mDataList.addAll(list);
            mOuter.mAdapter.notifyDataSetChanged();
            mOuter.mLoadingCover.onRefreshSuccess();

        }

        @Override
        public void onNoSatisfedData() {
            mOuter.mLoadingCover.onRefreshFailed(Define.MSG_NOTHING);
            mOuter.mFooterView.onRefreshComplete();
            mOuter.mPulListView.setOnScrollListener(null);
            if (mOuter.mPulListView.isRefreshing()){
                mOuter.mPulListView.getLoadingLayoutProxy().refreshSuccess();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            if (getRequestCode() == RequestCode.PULL){
                mOuter.mDataList.clear();
                mOuter.mAdapter.notifyDataSetChanged();
                ToastUtils.showToast(mOuter, "暂无内容");
            }

        }

        @Override
        public void onNoNetWork() {
            mOuter.mLoadingCover.onRefreshFailed();
            mOuter.mFooterView.onRefreshFailed();
            if (mOuter.mPulListView.isRefreshing()){
                mOuter.mPulListView.getLoadingLayoutProxy().refreshFailed();
            }
            if (getRequestCode() == RequestCode.SCROLL){
                mOuter.page--;
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter, Define.MSG_TOAST_NO_NETWORK);

        }

        @Override
        public void onResponseFailed() {
            mOuter.mLoadingCover.onRefreshFailed();
            mOuter.mFooterView.onRefreshFailed();
            if (getRequestCode() == RequestCode.SCROLL){
                mOuter.page--;
            }
            if (mOuter.mPulListView.isRefreshing()){
                mOuter.mPulListView.getLoadingLayoutProxy().refreshFailed();
            }
            if (mOuter.mLoadingData.isShowing()){
                mOuter.mLoadingData.dismiss();
            }
            ToastUtils.showToast(mOuter,"请求失败");
        }
    }

    /**
     *状态实体类
     */
    private class StatusInfo extends CustomerSpinnerObject{
        String id ;
        String name;

        public StatusInfo(String id, String name) {
            this.id = id;
            this.name = name;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return name;
        }
    }
}
